// pages/doTask/index.js
const qiniuUploader = require('../../utils/qiniuUploader')
var uploadImage = require('../../js/uploadImg/uploadAliyun.js');
const{
  getFormattedAddress
} =require('../../api/third')
const{
  AddUserCard
} =require('../../api/user')

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    project_id:0,
    note_text: '',
    task_id:0,
    fileList: [],
    token:'',
    filePath: '',
    longitude: '',
    latitude: '',
    imgUrl:[],
    current_location_str: ''
  },
  initQiniu() {
    var options = {
      region: 'SCN', // 华北区
      uptokenURL: 'https://api.fudaojiapu.com:8889/qiniu', //请求后端uptoken的url地址
      //uptoken: 'xxx',  //你请求后端的uptoken,和上面一样的，uptokenURL不填就找uptoken,填一个就可以了（这里是字符串数据不是url了）
      domain: 'https://img.fudaojiapu.com', //yourBucketId:这个去你域名配置那里要
      shouldUseQiniuFileName: false,
      //key: '' 
    };
    qiniuUploader.init(options);
  },
  afterRead(event) {
    const { file } = event.detail; // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    this.uploadImg(file);
  },
  delete(event) {
    console.log(event)
    let imgDelIndex = event.detail.index
    let fileList = this.data.fileList
    fileList.splice(imgDelIndex,1)
    console.log('删除图片的',fileList)
    this.setData({
        fileList
    })
  },
  didPressChooesImage(that) {
    initQiniu();
    // 微信 API 选文件
    wx.chooseImage({
        count: 1,
        success: function (res) {
          
        }
      })
  },
  uploadImg(file){
    //this.initQiniu();
    let scope=this
    var imgUrl =[];
    // 多张图片上传
    for(var i=0;i<file.length;i++){
      //var filePath = file[i].path;
      var filePath = file[i].path;
      uploadImage({
        filePath: filePath,
        dir: "lujinghua/",
        success: function (res) {
          const { fileList = [] } = scope.data;
          fileList.push({ ...file, url: res.imageURL });
          scope.setData({fileList})
          wx.hideLoading({
            complete: (res) => {},
          })
        },
        fail: function (res) {
          wx.hideLoading({
            complete: (res) => {},
          })
          wx.showModal({
            title: "温馨提示", // 提示的标题
            content: "上传失败，请重试！", // 提示的内容
            showCancel: false, // 是否显示取消按钮，默认true
            confirmText: "确定", // 确认按钮的文字，最多4个字符
            confirmColor: "#576B95", // 确认按钮的文字颜色，必须是 16 进制格式的颜色字符串
            success: function (res) {
              return
            }
          })
        }
      })
          
    }
    
  },
  submit(event) {
    console.log(this.data.fileList)
    if (this.data.fileList.length) {

      AddUserCard({fileList:this.data.fileList}).then(res=>{
        var pages = getCurrentPages(); //当前页面
        var beforePage = pages[pages.length - 2]; //前一页
        wx.navigateBack({
          success: function () {
            beforePage.onPullDownRefresh(); // 执行前一个页面的onLoad方法
          }
        });
      })
    }
    
  },
  onChange(event) {
    this.setData({
      note_text: event.detail,
    });
  },
  getLocationInfo() {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        complete: (res) => {},
        fail: (res) => {},
        success: ({
          longitude: lng,
          latitude: lat
        }) => {
          resolve({
            lat,
            lng
          })
        },
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: options.pn 
    })
    console.log(options)
    this.setData({
      task_id: options.task_id,
      project_id: options.id
    });
    this.getLocationInfo().then(res=> {
      getFormattedAddress({longitude: res.lng,latitude:res.lat}).then(response => {
        this.setData({
          longitude: res.lng,
          latitude: res.lat,
          current_location_str: response.data.currentLocationStr
        })
        wx.hideLoading({
          complete: (res) => {},
        })
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})